package com.trigsoft.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlSerializer;

import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.preference.PreferenceManager;
import android.util.Log;
import android.util.Xml;

import com.trigsoft.applist.DBHelper;
import com.trigsoft.applist.FileException;
import com.trigsoft.applist.NotInRecent;
import com.trigsoft.applist.R;
import com.trigsoft.applist.AppStatist.DateUtil;

public class PrefUtil
{
	private static String settingFile = "/sdcard/applist_settings.xml";
	private static String encoding = "UTF-8";
	static final String LEFT = "left";
	static final String RIGHT = "right";

	static final String TIME = "time";

	public static boolean checkAlphabetOnLeft(Context mContext)
	{
		return getPref(mContext, R.string.alphabetOnLeftKey);
	}

	public static boolean checkIntegrateStatistics(Context mContext)
	{
		return getPref(mContext, R.string.integrateStatisticsKey);
	}

	public static boolean checkRecentTask(Context mContext)
	{
		return getPref(mContext, R.string.recentTaskKey);
	}

	public static boolean checkShowCat(Context mContext)
	{
		// TODO Auto-generated method stub
		return getPref(mContext, R.string.showCatKey);
	}

	public static Boolean exportPref(Context context) throws FileException
	{
		XmlSerializer serializer = Xml.newSerializer();
		try
		{
			BufferedOutputStream writer = new BufferedOutputStream(new FileOutputStream(settingFile));

			try
			{
				serializer.setOutput(writer, encoding);
				serializer.startDocument(encoding, true);
				serializer.startTag("", "Settings");

				serializer.startTag("", context.getString(R.string.alphabetOnLeftKey));
				serializer.text(Boolean.toString(getPref(context, R.string.alphabetOnLeftKey)));
				serializer.endTag("", context.getString(R.string.alphabetOnLeftKey));

				serializer.startTag("", context.getString(R.string.recentTaskKey));
				serializer.text(Boolean.toString(getPref(context, R.string.recentTaskKey)));
				serializer.endTag("", context.getString(R.string.recentTaskKey));

				serializer.startTag("", context.getString(R.string.integrateStatisticsKey));
				serializer.text(Boolean.toString(getPref(context, R.string.integrateStatisticsKey)));
				serializer.endTag("", context.getString(R.string.integrateStatisticsKey));

				serializer.startTag("", context.getString(R.string.showCatKey));
				serializer.text(Boolean.toString(getPref(context, R.string.showCatKey)));
				serializer.endTag("", context.getString(R.string.showCatKey));

				serializer.startTag("", context.getString(R.string.addCatKey));
				serializer.text(PreferenceManager.getDefaultSharedPreferences(context).getString(
						context.getString(R.string.addCatKey), ""));
				serializer.endTag("", context.getString(R.string.addCatKey));

				Cursor cur = DBHelper.queryNotInRecentOrNotInListCat();
				if (cur.moveToFirst())
				{
					while (!cur.isAfterLast())
					{
						serializer.startTag("", "activity");
						serializer
								.attribute("", DBHelper.KEY_PKG, cur.getString(cur.getColumnIndex(DBHelper.KEY_NAME)));
						serializer.attribute("", DBHelper.KEY_NAME, cur
								.getString(cur.getColumnIndex(DBHelper.KEY_NAME)));
						serializer.attribute("", DBHelper.KEY_INLIST, Integer.toString(cur.getInt(cur
								.getColumnIndex(DBHelper.KEY_INLIST))));
						serializer.attribute("", DBHelper.KEY_INRECENT, Integer.toString(cur.getInt(cur
								.getColumnIndex(DBHelper.KEY_INRECENT))));
						serializer.attribute("", DBHelper.KEY_CAT, cur.getString(cur.getColumnIndex(DBHelper.KEY_CAT)));
						serializer.endTag("", "activity");
						cur.moveToNext();
					}
				}
				cur.close();

				NotInRecent nir = new NotInRecent(context);
				serializer.startTag("", "notinrecent");
				serializer.text(nir.getText());
				serializer.endTag("", "notinrecent");
				serializer.endTag("", "Settings");
				serializer.endDocument();
				Log.d("test", writer.toString());

			} finally
			{
				writer.close();
			}
			return true;
		} catch (FileNotFoundException e)
		{
			throw new FileException(settingFile + context.getString(R.string.fileNotFound));
		} catch (Exception e)
		{
			e.printStackTrace();
			return false;
		}
	}

	private static boolean getPref(Context context, Integer key)
	{
		return PreferenceManager.getDefaultSharedPreferences(context).getBoolean(context.getString(key), true);
	}

	public static Date getTime(Context mContext)
	{
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
		String time = prefs.getString(TIME, null);
		if (time == null)
			return null;
		return DateUtil.toDateFromPref(time);
	}

	public static Boolean importPref(Context ctx) throws FileException
	{
		XmlPullParser parser = Xml.newPullParser();
		try
		{
			BufferedInputStream in = new BufferedInputStream(new FileInputStream(settingFile));
			try
			{
				parser.setInput(in, encoding);
				int eventType = parser.getEventType();
				while (eventType != XmlPullParser.END_DOCUMENT)
				{
					String name = null;
					switch (eventType)
					{
					case XmlPullParser.START_DOCUMENT:
					case XmlPullParser.END_TAG:
						break;
					case XmlPullParser.START_TAG:
						name = parser.getName();
						if (name.equals(ctx.getString(R.string.alphabetOnLeftKey)))
						{
							setPref(ctx, R.string.alphabetOnLeftKey, new Boolean(parser.nextText()));
						} else if (name.equals(ctx.getString(R.string.integrateStatisticsKey)))
						{
							setPref(ctx, R.string.integrateStatisticsKey, new Boolean(parser.nextText()));
						} else if (name.equals(ctx.getString(R.string.recentTaskKey)))
						{
							setPref(ctx, R.string.recentTaskKey, new Boolean(parser.nextText()));
						} else if (name.equals(ctx.getString(R.string.showCatKey)))
						{
							setPref(ctx, R.string.showCatKey, new Boolean(parser.nextText()));
						} else if (name.equals(ctx.getString(R.string.addCatKey))
								|| name.equals(ctx.getString(R.string.oldAddCatKey)))
						{
							setAddCat(parser.nextText(), ctx);
						} else if (name.equals("activity"))
						{
							String n = parser.getAttributeValue("", DBHelper.KEY_NAME);
							Integer inlist = new Integer(parser.getAttributeValue("", DBHelper.KEY_INLIST));
							Integer inrecent = new Integer(parser.getAttributeValue("", DBHelper.KEY_INRECENT));
							String cat = parser.getAttributeValue("", DBHelper.KEY_CAT);
							if (cat == null)
								DBHelper.updateInlistInrecent(n, inlist, inrecent);
							else
								DBHelper.updateInlistInrecentCat(n, inlist, inrecent, cat);
						} else if (name.equals("notinrecent"))
						{
							new NotInRecent(ctx).importSetting(ctx, parser.nextText());
						}
						break;
					}
					eventType = parser.next();
				}

			} finally
			{
				in.close();
			}
			return true;
		} catch (FileNotFoundException e)
		{
			throw new FileException(settingFile + ctx.getString(R.string.fileNotFound));
		} catch (Exception e)
		{
			e.printStackTrace();
			return false;
		}
	}

	private static void setPref(Context ctx, Integer key, Boolean value)
	{
		SharedPreferences.Editor mEditor = PreferenceManager.getDefaultSharedPreferences(ctx).edit();
		mEditor.putBoolean(ctx.getString(key), value);
		mEditor.commit();
	}

	public static void updateTime(String d, Context mContext)
	{
		SharedPreferences.Editor prefs = PreferenceManager.getDefaultSharedPreferences(mContext).edit();
		prefs.putString(TIME, d);
		prefs.commit();
	}

	public static void addCat(String cat, Context mContext)
	{
		HashSet<String> catSet = getAddCat(mContext);
		String addCat;
		if (catSet.size() > 0)
		{
			StringBuilder sb = new StringBuilder();
			for (String c : catSet)
			{
				sb.append(c);
				sb.append(",");
			}
			sb.deleteCharAt(sb.length() - 1);
			addCat = sb.toString();
		} else
			addCat = cat;

		setAddCat(addCat, mContext);
	}

	public static HashSet<String> getAddCat(Context mContext)
	{
		String cats = PreferenceManager.getDefaultSharedPreferences(mContext).getString(
				mContext.getString(R.string.addCatKey), null);
		if (cats != null)
			return new HashSet<String>(Arrays.asList(cats.split(",")));
		return new HashSet<String>();
	}

	public static void setAddCat(String addCat, Context mContext)
	{
		SharedPreferences.Editor prefs = PreferenceManager.getDefaultSharedPreferences(mContext).edit();
		prefs.putString(mContext.getString(R.string.addCatKey), addCat);
		prefs.commit();
	}

	public static void upgradePref(Context mContext)
	{
		// TODO Auto-generated method stub
		SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(mContext);
		String cats = pref.getString(mContext.getString(R.string.oldAddCatKey), null);

		if (cats != null)
			pref.edit().putString(mContext.getString(R.string.addCatKey), cats);

		pref.edit().remove(mContext.getString(R.string.oldAddCatKey));
		pref.edit().commit();
	}

}
